<?php

function specialVariable($name){
    if ($name == "baseItemList"){
        if ($GLOBALS["lang"]["ac"] == "cz"){
            return parseTemplate(loadTemplate("eshop/itemList"));
        }
        if ($GLOBALS["lang"]["ac"] == "ru"){
            return parseTemplate(loadTemplate("eshop/itemListRU"));
        }
        if ($GLOBALS["lang"]["ac"] == "en"){
            return parseTemplate(loadTemplate("eshop/itemListEN"));
        }        
    }
}

/**
 * udela mezeru po kazde treti cifre od zadu (jako u ceny)
 * 
 * @param type $row
 * @param type $vypsat
 * @param type $numberType
 * @return type 
 */
function upravitNumber($row, $vypsat, $numberType) {
    if ($numberType == "cena") {
        $count = strlen($row[$vypsat]);
        $i = 0;
        $ret = "";
        $each = 0;
        while ($i < $count) {
            $negative = 0 - $i;
            if ($each == 3) {
                $ret = substr($row[$vypsat], $negative - 1, 1) . " " . $ret;
                $each = 0;
            } else {
                $ret = substr($row[$vypsat], $negative - 1, 1) . $ret;
            }
            $i++;
            $each++;
        }
        return $ret;
    }
    return $row[$vypsat];
}

function createColour($idcismap, $name) {
    //barva
    $textName = generateName();
    insertDynCisMapFK($idcismap, 4, getUser()->getLastImage());
    insertDynCisMapFK($idcismap, 1, $textName);
    createText($textName, $name, getUser()->getAdminId());
    $imgName = generateName();
    insertRecurrentId($textName, $imgName);
    createDefaultImage($imgName);

    //sklad   
    $skladIdCisMap = selectSkladDynCisMapId($idcismap);
    $result = selectCiselnikVelikosti();
    while ($row = mysql_fetch_array($result)) {
        $intName = generateName();
        insertDynCisMapFK($skladIdCisMap, 3, $intName);
        createInt($intName, 1, getUser()->getAdminId());
        insertRecurrentId($intName, $textName);
        insertRecurrentId($intName, $row["idval"]);
    }
}

function deleteColour($fkname) {
    $query = sprintf(SQL::$delete_colour, mysql_real_escape_string($fkname)
    );
    mq($query, $GLOBALS['link']);
    $result = getRecurrentMainId($fkname);
    while ($row = mysql_fetch_array($result)) {
        $query = sprintf(SQL::$delete_sklad, mysql_real_escape_string($row["idmain"])
        );
        mq($query, $GLOBALS['link']);
    }
}

function insertDynCisMapFK($idcismap, $idcis, $fkname) {
    $query = sprintf(SQL::$insert_dyncismap_full, mysql_real_escape_string($idcismap), mysql_real_escape_string($idcis), 0, mysql_real_escape_string($fkname)
    );
    $result = mq($query, $GLOBALS['link']);
}

function selectSkladDynCisMapId($idcismap) {
    $query = sprintf(SQL::$select_skladDynCisMapId, mysql_real_escape_string($idcismap));
    $query = mq($query, $GLOBALS["link"]);
    $row = mysql_fetch_array($query);
    return $row["idcismap"];
}

function selectDynCisMapId($itemId, $itemName) {
    $query = sprintf(SQL::$select_dyncismap_byItemId, mysql_real_escape_string($itemId), mysql_real_escape_string($itemName));
    $query = mq($query, $GLOBALS["link"]);
    $iddyncismap = mysql_fetch_array($query);
    return $iddyncismap["idcismap"];
}

function insertRecurrentId($maind, $linkid) {
    $query = sprintf(SQL::$insert_recurrentId, mysql_real_escape_string($maind), mysql_real_escape_string($linkid));
    mq($query, $GLOBALS["link"]);
}

function deleteImg($name) {
    $query = sprintf(SQL::$delete_img, mysql_real_escape_string($name));
    mq($query, $GLOBALS["link"]);
}

function deleteRecurrent($idLink) {
    $query = sprintf(SQL::$delete_recurrent, mysql_real_escape_string($idLink));
    mq($query, $GLOBALS["link"]);
}

function selectCiselnikVelikosti() {
    $query = sprintf(SQL::$select_ciselnik_velikosti);
    return mq($query, $GLOBALS["link"]);
}

function checkUserFakUdaje() {
    if (getUser()->getAdminId() == "" || getUser()->getAdminId() == null) {
        return false;
    } else {
        $query = sprintf(SQL::$select_adresa_userId, mysql_real_escape_string(getUser()->getAdminId()));
        $query = q($query);
        while ($row = mysql_fetch_array($query)) {
            return true;
        }
        return false;
    }
}

/**
 *
 * @param type $userId
 * @param type $ulice
 * @param type $mesto
 * @param type $psc
 * @param type $stat
 * @param type $mobil
 * @param type $firma
 * @param type $ic
 * @param type $typ
 * @return type 
 */
function insertAdresa($userId, $ulice, $mesto, $psc, $stat, $mobil, $firma, $ic, $typ, $jmeno, $prijmeni) {
    if (isEmpty($firma)) {
        $firma = "null";
    }
    if (isEmpty($ic)) {
        $ic = "null";
    }
    $query = sprintf(SQL::$insert_adresa, mysql_real_escape_string($userId), mysql_real_escape_string($ulice), mysql_real_escape_string($mesto), mysql_real_escape_string($psc), mysql_real_escape_string($stat), mysql_real_escape_string($mobil), mysql_real_escape_string($firma), mysql_real_escape_string($ic), mysql_real_escape_string($typ), mysql_real_escape_string($jmeno), mysql_real_escape_string($prijmeni)
    );
    return mq($query, $GLOBALS["link"]);
}

function updateAdresa($userId, $stav, $ulice, $mesto, $psc, $stat, $mobil, $firma, $ic, $jmeno, $prijmeni) {
    if (isEmpty($firma)) {
        $firma = "null";
    }
    if (isEmpty($ic)) {
        $ic = "null";
    }
    $query = sprintf(SQL::$update_adresa, mysql_real_escape_string($ulice), mysql_real_escape_string($mesto), mysql_real_escape_string($psc), mysql_real_escape_string($stat), mysql_real_escape_string($mobil), mysql_real_escape_string($firma), mysql_real_escape_string($ic), mysql_real_escape_string($jmeno), mysql_real_escape_string($prijmeni), mysql_real_escape_string($userId), mysql_real_escape_string($stav));
    return mq($query, $GLOBALS["link"]);
}

/**
 *
 * @param type $user
 * @param type $stav
 * @param type $odber
 * @return type 
 */
function insertOrder($user, $cenacelk, $stav, $odber) {
    $query = sprintf(SQL::$insert_order, mysql_real_escape_string($user), mysql_real_escape_string($cenacelk), mysql_real_escape_string($stav), mysql_real_escape_string($odber)
    );
    return mq($query, $GLOBALS["link"]);
}

/**
 *
 * @param type $orderId
 * @param type $itemId
 * @param type $znacka
 * @param type $velikost
 * @param type $mnozstvi
 * @param type $cena
 * @param type $stav
 * @return type 
 */
function insertOrderItems($orderId, $itemId, $znacka, $velikost, $mnozstvi, $cena, $stav) {
    $query = sprintf(SQL::$insert_orderitems, mysql_real_escape_string($orderId), mysql_real_escape_string($itemId), mysql_real_escape_string($znacka), mysql_real_escape_string($velikost), mysql_real_escape_string($mnozstvi), mysql_real_escape_string($cena), mysql_real_escape_string($stav)
    );
    return mq($query, $GLOBALS["link"]);
}

function registerUser($pass, $check, $email, $redirect = true) {
    if ($pass == $check) {
        $query = sprintf(SQL::$insert_user, mysql_real_escape_string($email), mysql_real_escape_string(hashByMatu($email, $pass)), mysql_real_escape_string($email), 'user');
        $result = q($query);
        if ($result) {
            login($email, $pass, $redirect);
        } else {
            header("location: " . Settings::$rootPath . Settings::$manager . "?action=" . Settings::$registerPage . "&msg=emailExist");
            exit();
        }
    } else {
        header("location: " . Settings::$rootPath . Settings::$manager . "?action=" . Settings::$registerPage . "&msg=kontrolaHesla");
        exit();
    }
}

function vytvorObednavku() {
    checkUser();
    insertOrder(getUser()->getAdminId(), getUser()->getCenaCelk(), Settings::$order_stav_zalozena, getUser()->getPlatba());
    $orderId = mysql_insert_id($GLOBALS["link"]);
    foreach (getUser()->getZbozi() as $value) {
        insertOrderItems($orderId, $value->getItemId(), $value->getBarva(), $value->getVelikost(), $value->getMnozstvi(), $value->getCena() * $value->getMnozstvi(), Settings::$zbozi_stav_pripravujeSe);
    }
    sendInfoMailAboutOrder();
    getUser()->removeZboziAll();
}

function sendInfoMailAboutOrder() {
    $message = "Uživatel si objednal zboží, podívejte se prosím do administrace. (Nástroje správce -> Správa objednávek)" . "\r\n\r\n" . "E-shop";

    // In case any of our lines are larger than 70 characters, we should use wordwrap()
    $to = 'petitelfeshop@gmail.com';
    $message = wordwrap($message, 70);
    $headers = 'From: petitelfeshop@gmail.com' . "\r\n" .
            'Reply-To: ' . $to . "\r\n" .
            'X-Mailer: PHP/' . phpversion();
    mail($to, 'NOVÁ OBJEDNÁVKA ', $message, $headers);
}

function setOrderStav($stav, $id) {
    $query = sprintf(SQL::$update_orderStav, mysql_real_escape_string($stav), mysql_real_escape_string($id));
    $query = q($query);
}

function vytbvorTabulkuObjednavky($id, $isUser = false) {
    $query = sprintf(SQL::$select_ordersAdminById, mysql_real_escape_string(Settings::$order_stav_nesmysl), mysql_real_escape_string($id));
    $query = q($query);
    $ret = '';
    global $objednavkaHeaderid;
    $objednavkaHeaderid = "";
    global $obejdnavkaHeaderdatum;
    $obejdnavkaHeaderdatum = "";
    global $objednavkaHeadermail;
    $objednavkaHeadermail = "";
    global $objednavkaHeadercena;
    $objednavkaHeadercena = "";
    global $objednavkaHeaderakce;
    $objednavkaHeaderakce = "";
    global $objednavkaUserBox;
    $objednavkaUserBox = "";
    global $objednavkaDorucBox;
    $objednavkaDorucBox = "";
    global $objednavkaZboziBox;
    $objednavkaZboziBox = "";
    global $telefon;
    $telefon = "";
    global $mail;
    $mail = "";
    global $jmeno;
    $jmeno = "";
    global $prijmeni;
    $prijmeni = "";
    global $ulice;
    $ulice = "";
    global $mesto;
    $mesto = "";
    global $psc;
    $psc = "";
    global $stat;
    $stat = "";
    global $firma;
    $firma = "";
    global $ico;
    $ico = "";
    global $djmeno;
    $djmeno = "";
    global $dprijmeni;
    $dprijmeni = "";
    global $dulice;
    $dulice = "";
    global $dmesto;
    $dmesto = "";
    global $dpsc;
    $dpsc = "";
    global $dfirma;
    $dfirma = "";
    global $dstat;
    $dstat = "";
    global $dico;
    $dico = "";
    global $nazevPredmetu;
    $nazevPredmetu = "";
    global $znackaPredmetu;
    $znackaPredmetu = "";
    global $velikostPredmetu;
    $velikostPredmetu = "";
    global $objednaneMnozstvi;
    $objednaneMnozstvi = "";
    global $cenaPredmetu;
    $cenaPredmetu = "";
    global $objednavkaHeadeStav;
    $objednavkaHeadeStav = "";
    global $zpusobOdberu;
    $zpusobOdberu = "";
    $oldOrderId = "nic";
    $first = true;
    $oncePerObjednavka = true;
    $DoncePerObjednavka = true;
    while ($row = mysql_fetch_array($query)) {
        if ($first) {
            $oldOrderId = $row["orderid"];
            $first = false;
        }
        if ($oldOrderId != $row["orderid"]) {
            $oncePerObjednavka = true;
            $DoncePerObjednavka = true;
            $objednavkaZboziBox = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/zboziDetail", "../"));
            $objednavkaUserBox = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/adresaDetail", "../"));
            $objednavkaDorucBox = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/dadresaDetail", "../"));
            if ($isUser) {
                
            } else {
                $objednavkaHeaderakce = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/akce", "../"));
            }
            $ret .= parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/objednavkaHeaderInside", "../"));
            $nazevPredmetu = "";
            $znackaPredmetu = "";
            $velikostPredmetu = "";
            $objednaneMnozstvi = "";
            $cenaPredmetu = "";
        }
        if ($row["adresaStav"] == Settings::$fakturacni) {
            $nazevPredmetu .= '<div class="tableRow">' . $row["item_name"] . '</div>';
            $znackaPredmetu .= '<div class="tableRow">' . $row["znacka"] . '</div>';
            $velikostPredmetu .= '<div class="tableRow">' . $row["velikost"] . '</div>';
            $objednaneMnozstvi .= '<div class="tableRow">' . $row["mnozstvi"] . '</div>';
            $cenaPredmetu .= '<div class="tableRow">' . $row["cena"] . '</div>';
            if ($oncePerObjednavka) {
                $objednavkaHeaderid = $row["orderid"];
                $obejdnavkaHeaderdatum = $row["cas"];
                $objednavkaHeadermail = $row["login"];
                $objednavkaHeadercena = $row["cenacelk"];
                $objednavkaHeadeStav = $row["stav"];

                $oncePerObjednavka = false;
                $telefon = $row["mobil"];
                $mail = $row["login"];
                $jmeno = $row["jmeno"];
                $prijmeni = $row["prijmeni"];
                $ulice = $row["ulice"];
                $mesto = $row["mesto"];
                $psc = $row["psc"];
                $zpusobOdberu = $row["odber"];
                if ($row["stat"] == 1) {
                    $stat = Settings::$stat_1;
                }
                if ($row["stat"] == 2) {
                    $stat = Settings::$stat_2;
                }
                $firma = isEmpty($row["firma"]) ? "" : $row["firma"];
                $ico = isEmpty($row["ic"]) ? "" : $row["ic"];
            }
        }
        if ($row["adresaStav"] == Settings::$dorucovaci) {
            if ($DoncePerObjednavka) {
                $DoncePerObjednavka = false;
                $djmeno = $row["jmeno"];
                $dprijmeni = $row["prijmeni"];
                $dulice = $row["ulice"];
                $dmesto = $row["mesto"];
                $dpsc = $row["psc"];

                if ($row["stat"] == 1) {
                    $dstat = Settings::$stat_1;
                }
                if ($row["stat"] == 2) {
                    $dstat = Settings::$stat_2;
                }
                $dfirma = isEmpty($row["firma"]) ? "" : $row["firma"];
                $dico = isEmpty($row["ic"]) ? "" : $row["ic"];
            }
        }

        $oldOrderId = $row["orderid"];
    }
    if (!$first) {
        $objednavkaZboziBox = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/zboziDetail", "../"));
        $objednavkaUserBox = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/adresaDetail", "../"));
        $objednavkaDorucBox = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/dadresaDetail", "../"));
        if ($isUser) {
            
        } else {
            $objednavkaHeaderakce = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/akce", "../"));
        }
        $ret .= parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/objednavkaHeaderInside", "../"));
    }
    $ret .= '</div>';
    return $ret;
}

function vytvorTabulkuObjednavekAdmin($id = null, $isUser = false) {
    if ($isUser) {
        if ($id != null) {
            $query = sprintf(SQL::$select_ordersUserById, mysql_real_escape_string(Settings::$order_stav_nesmysl), mysql_real_escape_string($id), mysql_real_escape_string(getUser()->getAdminId()));
        } else {
            $query = sprintf(SQL::$select_ordersUser, mysql_real_escape_string(Settings::$order_stav_nesmysl), mysql_real_escape_string(getUser()->getAdminId()));
        }
    } else {
        if ($id != null) {
            $query = sprintf(SQL::$select_ordersAdminById, mysql_real_escape_string(Settings::$order_stav_nesmysl), mysql_real_escape_string($id));
        } else {
            $query = sprintf(SQL::$select_ordersAdmin, mysql_real_escape_string(Settings::$order_stav_nesmysl));
        }
    }

    $query = q($query);
    $ret = '<div class="objednavkyWhole">';
    $ret .= parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/popisky", "../"));
    $ret .= '<div class="clear"> </div>';
    global $objednavkaHeaderid;
    $objednavkaHeaderid = "";
    global $obejdnavkaHeaderdatum;
    $obejdnavkaHeaderdatum = "";
    global $objednavkaHeadermail;
    $objednavkaHeadermail = "";
    global $objednavkaHeadercena;
    $objednavkaHeadercena = "";
    global $objednavkaHeaderakce;
    $objednavkaHeaderakce = "";
    global $objednavkaUserBox;
    $objednavkaUserBox = "";
    global $objednavkaDorucBox;
    $objednavkaDorucBox = "";
    global $objednavkaZboziBox;
    $objednavkaZboziBox = "";
    global $telefon;
    $telefon = "";
    global $mail;
    $mail = "";
    global $jmeno;
    $jmeno = "";
    global $prijmeni;
    $prijmeni = "";
    global $ulice;
    $ulice = "";
    global $mesto;
    $mesto = "";
    global $psc;
    $psc = "";
    global $djmeno;
    $djmeno = "";
    global $dprijmeni;
    $dprijmeni = "";
    global $dulice;
    $dulice = "";
    global $dmesto;
    $dmesto = "";
    global $dpsc;
    $dpsc = "";
    global $dfirma;
    $dfirma = "";
    global $dstat;
    $dstat = "";
    global $dico;
    $dico = "";
    global $stat;
    $stat = "";
    global $firma;
    $firma = "";
    global $ico;
    $ico = "";
    global $nazevPredmetu;
    $nazevPredmetu = "";
    global $znackaPredmetu;
    $znackaPredmetu = "";
    global $velikostPredmetu;
    $velikostPredmetu = "";
    global $objednaneMnozstvi;
    $objednaneMnozstvi = "";
    global $cenaPredmetu;
    $cenaPredmetu = "";
    global $objednavkaHeadeStav;
    $objednavkaHeadeStav = "";
    global $zpusobOdberu;
    $zpusobOdberu = "";
    $oldOrderId = "nic";
    $first = true;
    $oncePerObjednavka = true;
    $DoncePerObjednavka = true;
    while ($row = mysql_fetch_array($query)) {
        if ($first) {
            $oldOrderId = $row["orderid"];
            $first = false;
        }
        if ($oldOrderId != $row["orderid"]) {
            $oncePerObjednavka = true;
            $DoncePerObjednavka = true;
            $objednavkaZboziBox = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/zboziDetail", "../"));
            $objednavkaUserBox = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/adresaDetail", "../"));
            $objednavkaDorucBox = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/dadresaDetail", "../"));
            if ($isUser) {
                
            } else {
                $objednavkaHeaderakce = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/akce", "../"));
            }

            $ret .= parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/ObjednavkaHeader", "../"));
            $nazevPredmetu = "";
            $znackaPredmetu = "";
            $velikostPredmetu = "";
            $objednaneMnozstvi = "";
            $cenaPredmetu = "";
        }
        if ($row["adresaStav"] == Settings::$fakturacni) {
            $nazevPredmetu .= '<div class="tableRow">' . $row["item_name"] . '</div>';
            $znackaPredmetu .= '<div class="tableRow">' . $row["znacka"] . '</div>';
            $velikostPredmetu .= '<div class="tableRow">' . $row["velikost"] . '</div>';
            $objednaneMnozstvi .= '<div class="tableRow">' . $row["mnozstvi"] . '</div>';
            $cenaPredmetu .= '<div class="tableRow">' . $row["cena"] . '</div>';
            if ($oncePerObjednavka) {
                $objednavkaHeaderid = $row["orderid"];
                $obejdnavkaHeaderdatum = $row["cas"];
                $objednavkaHeadermail = $row["login"];
                $objednavkaHeadercena = $row["cenacelk"];
                $objednavkaHeadeStav = $row["stav"];

                $oncePerObjednavka = false;
                $telefon = $row["mobil"];
                $mail = $row["login"];
                $jmeno = $row["jmeno"];
                $prijmeni = $row["prijmeni"];
                $ulice = $row["ulice"];
                $mesto = $row["mesto"];
                $psc = $row["psc"];
                $zpusobOdberu = $row["odber"];
                if ($row["stat"] == 1) {
                    $stat = Settings::$stat_1;
                }
                if ($row["stat"] == 2) {
                    $stat = Settings::$stat_2;
                }
                $firma = isEmpty($row["firma"]) ? "" : $row["firma"];
                $ico = isEmpty($row["ic"]) ? "" : $row["ic"];
            }
        }

        if ($row["adresaStav"] == Settings::$dorucovaci) {
            if ($DoncePerObjednavka) {
                $DoncePerObjednavka = false;
                $djmeno = $row["jmeno"];
                $dprijmeni = $row["prijmeni"];
                $dulice = $row["ulice"];
                $dmesto = $row["mesto"];
                $dpsc = $row["psc"];

                if ($row["stat"] == 1) {
                    $dstat = Settings::$stat_1;
                }
                if ($row["stat"] == 2) {
                    $dstat = Settings::$stat_2;
                }
                $dfirma = isEmpty($row["firma"]) ? "" : $row["firma"];
                $dico = isEmpty($row["ic"]) ? "" : $row["ic"];
            }
        }

        $oldOrderId = $row["orderid"];
    }
    if (!$first) {
        $objednavkaZboziBox = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/zboziDetail", "../"));
        $objednavkaUserBox = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/adresaDetail", "../"));
        $objednavkaDorucBox = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/dadresaDetail", "../"));
        if ($isUser) {
            
        } else {
            $objednavkaHeaderakce = parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/akce", "../"));
        }
        $ret .= parseTemplate(loadTemplateWithPath(Settings::$template_path . "eshop/itemListDiv/spravaObjednavek/ObjednavkaHeader", "../"));
    }
    $ret .= '</div>';
    return $ret;
}

function getAdresaByUser() {
    $query = sprintf(SQL::$select_adresa_userId, mysql_real_escape_string(getUser()->getAdminId()));
    return q($query);
}

?>
